import { _decorator, Component, Label, Material, Node, UITransform } from 'cc';
const { ccclass, property, requireComponent } = _decorator;

@ccclass('LabelLine')
@requireComponent(Label)
export class LabelLine extends Component {
    @property(Material)
    sharedMat: Material = null!;

    private label: Label = null!;

    private _material = new Material();
    protected onLoad(): void {
        this.label = this.getComponent(Label)!;
        this._material.copy(this.sharedMat);
    }
    start() {
        let line = getLabelLineCount(this.label);
        this._material.setProperty('Line', line);
        this.label.customMaterial = this._material;
    }
}

function getLabelLineCount(label: Label): number {
    // 确保文本已经渲染完成
    label.updateRenderData(true); // 强制更新渲染数据（仅限 2.x 或部分 3.x 版本）

    const height = label.node.getComponent(UITransform)!.contentSize.height;
    const lineHeight = label.lineHeight;
    return Math.round(height / lineHeight);
}
